/**
 * Contract Update Manager Component (Simplified)
 * Provides interface for updating contract parameters
 */

import React, { useState, useEffect } from 'react';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
  Settings,
  AlertTriangle,
  CheckCircle,
  Clock,
  X,
  Send,
  RefreshCw,
  Eye,
  Shield,
  Coins,
  Users,
  Zap,
  Ban
} from 'lucide-react';

interface ContractUpdateManagerProps {
  contractName: string;
}

interface SupportedOperation {
  name: string;
  description: string;
  parameters: {
    name: string;
    type: string;
    description: string;
    required: boolean;
    options?: string[];
  }[];
  riskLevel: 'low' | 'medium' | 'high';
}

const ContractUpdateManager: React.FC<ContractUpdateManagerProps> = ({ contractName }) => {
  const [selectedOperation, setSelectedOperation] = useState<string>('');
  const [parameters, setParameters] = useState<Record<string, any>>({});
  const [reason, setReason] = useState<string>('');
  const [showCurrentState, setShowCurrentState] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Mock supported operations
  const supportedOperations: Record<string, SupportedOperation[]> = {
    dtv_token: [
      {
        name: 'setBlacklist',
        description: 'Add or remove addresses from blacklist',
        parameters: [
          { name: 'address', type: 'text', description: 'Wallet address to blacklist/unblacklist', required: true },
          { name: 'blacklisted', type: 'select', options: ['true', 'false'], description: 'true to blacklist, false to unblacklist', required: true }
        ],
        riskLevel: 'high'
      },
      {
        name: 'setFeeRates',
        description: 'Update transaction and burn fee rates',
        parameters: [
          { name: 'transactionFeeRate', type: 'number', description: 'Transaction fee rate (basis points)', required: true },
          { name: 'burnFeeRate', type: 'number', description: 'Burn fee rate (basis points)', required: true }
        ],
        riskLevel: 'high'
      },
      {
        name: 'setAntiBotConfig',
        description: 'Configure anti-bot mechanisms',
        parameters: [
          { name: 'enabled', type: 'select', options: ['true', 'false'], description: 'Enable/disable anti-bot', required: true },
          { name: 'duration', type: 'number', description: 'Anti-bot duration (seconds)', required: true },
          { name: 'delay', type: 'number', description: 'Anti-bot delay (seconds)', required: true }
        ],
        riskLevel: 'medium'
      },
      {
        name: 'setFeeExemption',
        description: 'Set fee exemption for addresses',
        parameters: [
          { name: 'address', type: 'text', description: 'Address to exempt from fees', required: true },
          { name: 'exempt', type: 'select', options: ['true', 'false'], description: 'true to exempt, false to remove exemption', required: true }
        ],
        riskLevel: 'medium'
      }
    ],
    dtv_mining: [
      {
        name: 'setMiningParameters',
        description: 'Update mining parameters',
        parameters: [
          { name: 'parameter', type: 'select', options: ['mining_release_rate', 'reward_distribution_rate', 'daily_reward_cap'], description: 'Parameter to update', required: true },
          { name: 'value', type: 'number', description: 'New parameter value (rates in basis points: 1%=100, 1.1%=110, cap: integer >= 0)', required: true }
        ],
        riskLevel: 'medium'
      }
    ]
  };

  // Mock contract state
  const contractState = {
    transactionFeeRate: '200',
    burnFeeRate: '50',
    antiBotEnabled: 'true',
    totalSupply: '10000000000'
  };

  // Real update history
  const [updateHistory, setUpdateHistory] = useState<any[]>([]);
  
  // Fetch update history
  useEffect(() => {
    const fetchHistory = async () => {
      try {
        const response = await fetch(`/api/v1/contracts/admin/history?contract_name=${contractName}`);
        if (response.ok) {
          const data = await response.json();
          setUpdateHistory(data.updates || []);
        }
      } catch (error) {
        console.error('Error fetching update history:', error);
      }
    };
    
    fetchHistory();
  }, [contractName]);

  const currentOperations = supportedOperations[contractName] || [];
  const currentOperation = currentOperations.find(op => op.name === selectedOperation);

  const handleParameterChange = (paramName: string, value: any) => {
    setParameters(prev => ({
      ...prev,
      [paramName]: value
    }));
  };

  const handleSubmit = async () => {
    if (!selectedOperation || !reason.trim()) {
      alert('Please select an operation and provide a reason');
      return;
    }

    // Validate required parameters
    const requiredParams = currentOperation?.parameters.filter(p => p.required) || [];
    const missingParams = requiredParams.filter(p => !parameters[p.name] && parameters[p.name] !== 0);
    
    if (missingParams.length > 0) {
      alert(`Please provide: ${missingParams.map(p => p.name).join(', ')}`);
      return;
    }

    // Special validation for mining parameters
    if (selectedOperation === 'setMiningParameters') {
      const parameter = parameters.parameter;
      const value = Number(parameters.value);
      
      if (isNaN(value)) {
        alert('Value must be a valid number');
        return;
      }
      
      if (!Number.isInteger(value)) {
        alert('Value must be a whole number (integer)');
        return;
      }
      
      if ((parameter === 'mining_release_rate' || parameter === 'reward_distribution_rate') && (value < 0 || value > 10000)) {
        alert('Release rates and distribution rates must be between 0 and 10000 basis points (0% to 100%)');
        return;
      }
      
      if (parameter === 'daily_reward_cap' && value < 0) {
        alert('Daily reward cap must be greater than or equal to 0');
        return;
      }
    }

    setIsSubmitting(true);
    
    try {
      // Convert parameters for backend compatibility  
      let apiParameters = JSON.parse(JSON.stringify(parameters)); // Deep copy
      
      // Handle mining parameters conversion
      if (selectedOperation === 'setMiningParameters') {
        const paramType = apiParameters.parameter;
        const rawValue = apiParameters.value;
        
        // Convert basis points to decimal for rate parameters
        if (paramType === 'mining_release_rate' || paramType === 'reward_distribution_rate') {
          // User enters basis points (e.g., 80), backend needs decimal (e.g., 0.008)
          apiParameters.value = Number(rawValue) / 10000;
        } else if (paramType === 'daily_reward_cap') {
          // Daily reward cap stays as integer
          apiParameters.value = Number(rawValue);
        }
      }
      
      // Make actual API call to backend
      const response = await fetch('/api/v1/contracts/admin/update', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          contract_name: contractName,
          operation: selectedOperation,
          parameters: apiParameters,
          reason: reason,
        }),
      });

      if (!response.ok) {
        // If API endpoint doesn't exist, show detailed request information
        if (response.status === 404) {
          const requestInfo = {
            contract_name: contractName,
            operation: selectedOperation,
            parameters: parameters,
            reason: reason,
          };
          
          console.log('Contract Update Request:', requestInfo);
          
          alert(`Contract Update Request Logged:
Contract: ${contractName}
Operation: ${selectedOperation}
Parameters: ${JSON.stringify(parameters, null, 2)}
Reason: ${reason}

This request has been logged to the console. The backend API endpoint will be implemented to handle actual contract updates.`);
          
          // Clear form after successful "submission"
          setSelectedOperation('');
          setParameters({});
          setReason('');
          return;
        }
        
        const errorData = await response.json();
        throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      
      alert(`Update submitted successfully! Transaction hash: ${result.transaction_hash || 'N/A'}`);
      setSelectedOperation('');
      setParameters({});
      setReason('');
      
      // Refresh history
      try {
        const response = await fetch(`/api/v1/contracts/admin/history?contract_name=${contractName}`);
        if (response.ok) {
          const data = await response.json();
          setUpdateHistory(data.updates || []);
        }
      } catch (error) {
        console.error('Error refreshing history:', error);
      }
    } catch (error) {
      console.error('Contract update error:', error);
      alert(`Error submitting update: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsSubmitting(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'text-green-600';
      case 'failed': return 'text-red-600';
      case 'pending': return 'text-yellow-600';
      default: return 'text-gray-600';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return CheckCircle;
      case 'failed': return X;
      case 'pending': return Clock;
      default: return Clock;
    }
  };

  const getRiskColor = (riskLevel: string) => {
    switch (riskLevel) {
      case 'high': return 'bg-red-100 text-red-800';
      case 'medium': return 'bg-yellow-100 text-yellow-800';
      case 'low': return 'bg-green-100 text-green-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getOperationIcon = (operation: string) => {
    if (operation.includes('Fee')) return Coins;
    if (operation.includes('Blacklist')) return Ban;
    if (operation.includes('Exemption')) return Shield;
    if (operation.includes('AntiBot')) return Users;
    if (operation.includes('Mining')) return Zap;
    return Settings;
  };

  return (
    <div className="space-y-6">
      {/* Operation Selection */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="w-5 h-5" />
            Select Operation
          </CardTitle>
          <CardDescription>
            Choose the contract parameter you want to update
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {currentOperations.map((operation) => {
              const Icon = getOperationIcon(operation.name);
              return (
                <div
                  key={operation.name}
                  onClick={() => setSelectedOperation(operation.name)}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    selectedOperation === operation.name
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <Icon className="w-4 h-4" />
                      <span className="font-medium">{operation.name}</span>
                    </div>
                    <span className={`px-2 py-1 rounded text-xs font-medium ${getRiskColor(operation.riskLevel)}`}>
                      {operation.riskLevel.toUpperCase()}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600">{operation.description}</p>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Parameter Input */}
      {currentOperation && (
        <Card>
          <CardHeader>
            <CardTitle>Configure Parameters</CardTitle>
            <CardDescription>
              Enter the values for {currentOperation.name}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {currentOperation.parameters.map((param) => (
                <div key={param.name}>
                  <Label htmlFor={param.name} className="flex items-center gap-2">
                    {param.name}
                    {param.required && <span className="text-red-500">*</span>}
                  </Label>
                  {param.type === 'select' ? (
                    <select
                      id={param.name}
                      value={parameters[param.name] || ''}
                      onChange={(e) => handleParameterChange(param.name, e.target.value)}
                      className="w-full mt-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">Select {param.name}</option>
                      {param.options?.map((option) => (
                        <option key={option} value={option}>{option}</option>
                      ))}
                    </select>
                  ) : (
                    <Input
                      id={param.name}
                      type={param.type === 'number' ? 'number' : 'text'}
                      placeholder={param.description}
                      value={parameters[param.name] || ''}
                      onChange={(e) => handleParameterChange(param.name, 
                        param.type === 'number' ? Number(e.target.value) : e.target.value
                      )}
                      className="mt-1"
                    />
                  )}
                  <p className="text-xs text-gray-500 mt-1">{param.description}</p>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Reason Input */}
      {selectedOperation && (
        <Card>
          <CardHeader>
            <CardTitle>Reason for Update</CardTitle>
            <CardDescription>
              Provide a clear reason for this contract update
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Textarea
              placeholder="Enter the reason for this update..."
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              className="min-h-[100px]"
            />
          </CardContent>
        </Card>
      )}

      {/* Submit Button */}
      {selectedOperation && (
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={() => setShowCurrentState(!showCurrentState)}
            >
              <Eye className="w-4 h-4 mr-2" />
              {showCurrentState ? 'Hide' : 'Show'} Current State
            </Button>
          </div>
          <Button
            onClick={handleSubmit}
            disabled={isSubmitting}
            className="bg-blue-600 hover:bg-blue-700"
          >
            {isSubmitting ? (
              <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Send className="w-4 h-4 mr-2" />
            )}
            Submit Update
          </Button>
        </div>
      )}

      {/* Current State */}
      {showCurrentState && (
        <Card>
          <CardHeader>
            <CardTitle>Current Contract State</CardTitle>
            <CardDescription>
              Current parameter values for {contractName}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {Object.entries(contractState).map(([key, value]) => (
                <div key={key} className="flex justify-between items-center p-2 bg-gray-50 rounded">
                  <span className="font-medium">{key}:</span>
                  <span className="px-2 py-1 bg-white rounded border text-sm">{String(value)}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Update History */}
      <Card>
        <CardHeader>
          <CardTitle>Recent Updates</CardTitle>
          <CardDescription>
            Recent contract update requests for {contractName}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {updateHistory.slice(0, 5).map((update) => {
              const StatusIcon = getStatusIcon(update.status);
              return (
                <div key={update.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <StatusIcon className={`w-4 h-4 ${getStatusColor(update.status)}`} />
                    <div>
                      <div className="font-medium">{update.operation}</div>
                      <div className="text-sm text-gray-600">{update.reason || 'No reason provided'}</div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className={`text-sm font-medium ${getStatusColor(update.status)}`}>
                      {update.status.toUpperCase()}
                    </div>
                    <div className="text-xs text-gray-500">
                      {new Date(update.created_at || update.timestamp).toLocaleString()}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default ContractUpdateManager;